import React, { useEffect, useState } from "react";
import { Card, Button, Form, Input, Select, Table, Space, message } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router";
import type { ColumnsType } from "antd/es/table";
import {
  reqGetHospitalList,
  reqGetProvinceCodeList,
  reqGetCityOrDistrictCodeList,
  reqUpdateStatus,
} from "@/api/hospital/hospitalList/index";
import {
  IHospitalItem,
  IHospitalList,
  ProvinceCodeList,
} from "@/api/hospital/hospitalList/model/hospitalListTypes";

const HospitalList = () => {
  const navigate = useNavigate();
  // 获取form实例
  const [form] = Form.useForm();
  // 分页数据
  const [pageSize, setPageSize] = useState(5);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [hospitalList, setHospitalList] = useState<IHospitalList>([]);
  // 省数据
  const [province, setProvince] = useState<ProvinceCodeList>([]);
  // 市区数据
  const [city, setCity] = useState<ProvinceCodeList>([]);
  const [district, setDistrict] = useState<ProvinceCodeList>([]);

  // 医院等级数据
  const [hostypeString, setHostypeString] = useState<ProvinceCodeList>([]);

  let flag = false;
  // 条件查询
  const onFinish = (values: any) => {
    console.log(values);
    flag = true;
    getHospitalList(1, pageSize);
    setPage(1);
  };
  // 清空
  const clear = () => {
    flag = false;
    // 清空输入框数据
    form.setFieldsValue({
      cityCode: undefined,
      districtCode: undefined,
      hoscode: undefined,
      hosname: undefined,
      hostype: undefined,
      provinceCode: undefined,
      status: undefined,
    });
    // 获取列表，从第一页
    getHospitalList(1, pageSize);
    setPage(1);
  };
  // 分页获取医院列表
  const getHospitalList = async (page: number, pageSize: number) => {
    let res;
    if (flag) {
      const params = form.getFieldsValue();
      console.log(params);

      res = await reqGetHospitalList({ page, limit: pageSize, ...params });
    } else {
      res = await reqGetHospitalList({ page, limit: pageSize });
    }
    setHospitalList(res.content);
    setTotal(res.totalElements);
  };

  // 获取省列表
  const getProvinceCodeList = async () => {
    const res = await reqGetProvinceCodeList();
    setProvince(res);
  };
  useEffect(() => {
    getHospitalList(page, pageSize);
    getProvinceCodeList();
    getHostypeStringList();
  }, []);
  // 根据省获取市
  const provinceChange = async (value: string) => {
    // console.log(`selected ${value}`);
    const res = await reqGetCityOrDistrictCodeList(value);
    setCity(res);
  };
  // 根据市获取区域
  const cityChange = async (value: string) => {
    // console.log(`selected ${value}`);
    const res = await reqGetCityOrDistrictCodeList(value);
    setDistrict(res);
  };
  // 获取医院等级
  const getHostypeStringList = async () => {
    const res = await reqGetCityOrDistrictCodeList("10000");
    setHostypeString(res);
  };
  // 行
  const columns: ColumnsType<IHospitalItem> = [
    {
      title: "序号",
      align: "center",
      width: 80,
      // 当前行的值，当前行数据，行索引
      render(text, record, index) {
        return index + 1;
      },
    },
    {
      title: "医院logo",
      dataIndex: "logoData",
      render(text) {
        return <img src={`data:image/jpeg;base64,` + text} alt="" width={80} />;
      },
      align: "center",
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "等级",
      // 当前行的值，当前行数据，行索引
      render(data) {
        return data.param.hostypeString;
      },
    },
    {
      title: "详细地址",
      render(data) {
        return data.param.fullAddress;
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      render(date) {
        return date ? "上线" : "下线";
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      dataIndex: "action",
      width: 250,
      // 当前行的值，当前行数据，行索引
      render(_, record) {
        // 处理批量删除按钮是否禁用的状态
        // const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([])
        return (
          <Space size="middle">
            <Button type="primary" size="middle" onClick={() => {
               navigate(
                `/syt/hospital/hospitalList/show/${record.id}`
              );
            }}>
              查看
            </Button>
            <Button
              type="primary"
              size="middle"
              onClick={() => {
                navigate(
                  `/syt/hospital/hospitalList/schedule/${record.hoscode}`
                );
              }}
            >
              排班
            </Button>
            <Button
              type="primary"
              size="middle"
              onClick={async () => {
                // console.log(record);
                const { id, status } = record;
                await reqUpdateStatus(id, status ? 0 : 1);
                getHospitalList(page, pageSize);
                message.success("更新医院状态成功");
              }}
            >
              {record.status ? "下线" : "上线"}
            </Button>
          </Space>
        );
      },
    },
  ];

  return (
    <Card style={{ minHeight: "calc(100vh - 64px)" }}>
      <Form
        layout="inline"
        name="basic"
        form={form}
        onFinish={onFinish}
        onValuesChange={() => {
          flag = flag;
        }}
      >
        <Form.Item style={{ width: 200 }} name="provinceCode">
          <Select
            onChange={provinceChange}
            options={province.map((item) => {
              return {
                label: item.name,
                value: item.id,
              };
            })}
            placeholder="请选择省"
          />
        </Form.Item>
        <Form.Item style={{ width: 200 }} name="cityCode">
          <Select
            onChange={cityChange}
            options={city.map((item) => {
              return {
                label: item.name,
                value: item.id,
              };
            })}
            placeholder="请选择市"
          />
        </Form.Item>
        <Form.Item style={{ width: 200 }} name="districtCode">
          <Select
            options={district.map((item) => {
              return {
                label: item.name,
                value: item.id,
              };
            })}
            placeholder="请选择区"
          />
        </Form.Item>
        <Form.Item name="hosname" style={{ width: 200 }}>
          <Input placeholder="医院名称" />
        </Form.Item>
        <Form.Item name="hoscode" style={{ width: 200 }}>
          <Input placeholder="医院编码" />
        </Form.Item>

        <Form.Item style={{ width: 200, marginTop: 30 }} name="hostype">
          <Select
            options={hostypeString.map((item) => {
              return {
                label: item.name,
                value: item.value,
              };
            })}
            placeholder="医院类型"
          />
        </Form.Item>

        <Form.Item style={{ width: 200, marginTop: 30 }} name="status">
          <Select
            options={[
              { value: 1, label: "上线" },
              { value: 0, label: "下线" },
            ]}
            placeholder="医院状态"
          />
        </Form.Item>
        <Form.Item style={{ marginTop: 30 }}>
          <Button
            type="primary"
            icon={<SearchOutlined />}
            style={{ marginRight: 10 }}
            htmlType="submit"
          >
            查询
          </Button>
          <Button type="default" onClick={clear}>
            清空
          </Button>
        </Form.Item>
      </Form>
      <Table
        dataSource={hospitalList}
        columns={columns}
        bordered
        style={{ marginTop: 20 }}
        rowKey={"id"}
        pagination={{
          total,
          current: page,
          pageSize,
          showTotal(total, render) {
            return `共${total}条`;
          },
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: [5, 10, 15, 20],
          onChange(page, pageSize) {
            // console.log(page, pageSize);
            flag = true;
            setPageSize(pageSize);
            setPage(page);
            getHospitalList(page, pageSize);
          },
        }}
      />
    </Card>
  );
};

export default HospitalList;
